// packageA/pages/category/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        categoryList: [],
        showModal: false,
        currentCategory: {
            id: '',
            name: '',
            icon: '',
            sort: 0,
            isShow: true
        },
        actionType: 'add' // add or edit
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.loadCategories();
    },
    loadCategories() {
        wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.GetAllCategoriesAsync", {
        }).then((res) => {
            if (res.success) {
                console.log('分类：' + res.data);
                // 拿到分类
                const categories = res.data || [];
                this.setData({
                    categoryList: categories.sort((a, b) => b.sort - a.sort)
                });
            } else {
                console.log(res.errorMessage)
            }
        })

    },

    addCategory() {
        this.setData({
            showModal: true,
            currentCategory: {
                id: Date.now().toString(),
                name: '',
                icon: '',
                sort: 0,
                isShow: true
            },
            actionType: 'add'
        });
    },

    editCategory(e) {
        const id = e.currentTarget.dataset.id;
        const category = this.data.categoryList.find(item => item.id === id);
        this.setData({
            showModal: true,
            currentCategory: { ...category },
            actionType: 'edit'
        });
    },

    deleteCategory(e) {
        const id = e.currentTarget.dataset.id;
        wx.showModal({
            title: '提示',
            content: '确定要删除这个分类吗？',
            success: (res) => {
                if (res.confirm) {
                    wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.DeleteCategoryAsync", {
                        id,
                        Name : this.data.currentCategory.name,
                        Sort: this.data.currentCategory.sort,
                        IsShow: this.data.currentCategory.isShow,
                        Icon: this.data.currentCategory.icon
                    }).then((res) => {
                        if (res.success) {
                            console.log('删除分类：' + res.data);
                            if (res.data) {
                                this.loadCategories();
                                this.hideModal();
                            }

                            //    let currentCategory= {
                            //         id: Date.now().toString(),
                            //         name: res.data.name,
                            //         icon: res.data.icon,
                            //         sort: res.data.sort,
                            //         isShow: res.data.isShow
                            //     },
                            //     // 拿到分类
                            //     newList = [...categoryList, currentCategory];
                        } else {
                            console.log(res.errorMessage)
                        }
                    })
                    // const newList = this.data.categoryList.filter(item => item.id !== id);
                    // wx.setStorageSync('categories', newList);
                    this.loadCategories();
                }
            }
        });
    },

    chooseIcon() {
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album'],
            success: (res) => {
                const tempFilePaths = res.tempFilePaths;
                this.setData({
                    'currentCategory.icon': tempFilePaths[0]
                });
            }
        });
    },

    inputName(e) {
        this.setData({
            'currentCategory.name': e.detail.value
        });
    },

    inputSort(e) {
        this.setData({
            'currentCategory.sort': parseInt(e.detail.value) || 0
        });
    },

    toggleShow(e) {
        const id = e.currentTarget.dataset.id;
        const result = this.data.categoryList.find(item => item.id === id);
        wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.UpdateCategoryAsync", {
            id: result.id,
            Name : result.name,
            Sort: result.sort,
            IsShow: !result.isShow,
            // Icon: result.icon
        }).then((res) => {
            if (res.success) {
                console.log('新分类：' + res.data);
                this.loadCategories();
                this.hideModal();
                //    let currentCategory= {
                //         id: Date.now().toString(),
                //         name: res.data.name,
                //         icon: res.data.icon,
                //         sort: res.data.sort,
                //         isShow: res.data.isShow
                //     },
                //     // 拿到分类
                //     newList = [...categoryList, currentCategory];
            } else {
                console.log(res.errorMessage)
            }
        })
        // const newList = this.data.categoryList.map(item => {
        //     if (item.id === id) {
        //         return { ...item, isShow: !item.isShow };
        //     }
        //     return item;
        // });
        // wx.setStorageSync('categories', newList);
        this.loadCategories();
    },

    toggleCurrentShow(e) {
        this.setData({
            'currentCategory.isShow': e.detail.value
        });
    },

    hideModal() {
        this.setData({
            showModal: false
        });
    },

    confirmAction() {
        const { currentCategory, actionType, categoryList } = this.data;

        if (!currentCategory.name) {
            wx.showToast({
                title: '请输入分类名称',
                icon: 'none'
            });
            return;
        }

        let newList = [];
        if (actionType === 'add') {
            wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.CreateCategoryAsync", {
                Name : this.data.currentCategory.name,
                Sort: this.data.currentCategory.sort,
                IsShow: this.data.currentCategory.isShow,
                // Icon: this.data.currentCategory.icon
            }).then((res) => {
                if (res.success) {
                    console.log('新分类：' + res.data);
                    this.loadCategories();
                    this.hideModal();
                    //    let currentCategory= {
                    //         id: Date.now().toString(),
                    //         name: res.data.name,
                    //         icon: res.data.icon,
                    //         sort: res.data.sort,
                    //         isShow: res.data.isShow
                    //     },
                    //     // 拿到分类
                    //     newList = [...categoryList, currentCategory];
                } else {
                    console.log(res.errorMessage)
                }
            })

        } else {
            wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.UpdateCategoryAsync", {
                id: this.data.currentCategory.id,
                Name : this.data.currentCategory.name,
                Sort: this.data.currentCategory.sort,
                IsShow: this.data.currentCategory.isShow,
                // Icon: this.data.currentCategory.icon
            }).then((res) => {
                if (res.success) {
                    console.log('新分类：' + res.data);
                    this.loadCategories();
                    this.hideModal();
                    //    let currentCategory= {
                    //         id: Date.now().toString(),
                    //         name: res.data.name,
                    //         icon: res.data.icon,
                    //         sort: res.data.sort,
                    //         isShow: res.data.isShow
                    //     },
                    //     // 拿到分类
                    //     newList = [...categoryList, currentCategory];
                } else {
                    console.log(res.errorMessage)
                }
            })
            // newList = categoryList.map(item => {
            //     if (item.id === currentCategory.id) {
            //         return currentCategory;
            //     }
            //     return item;
            // });
        }

        // wx.setStorageSync('categories', newList);
        // this.loadCategories();
        // this.hideModal();
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})